package org.vehicle.iface;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.net.ftp.FTPClient;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.util.Base64Utils;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.vehicle.entity.AlertInfo;
import org.vehicle.entity.ManagerInfo;
import org.vehicle.entity.PersonInfo;
import org.vehicle.entity.VehicleInfo;
import org.vehicle.service.AlertInfoService;
import org.vehicle.service.PersonInfoService;
import org.vehicle.service.VehicleInfoService;
import org.vehicle.service.redis.RedisService;
import org.vehicle.util.CommonUtil;
import org.vehicle.util.FtpUtil;
import org.vehicle.util.JsonUtils;
import org.vehicle.util.StringUtil;
import org.vehicle.vo.DevicePersonPageVO;
import org.vehicle.vo.DevicePersonVO;

import com.fasterxml.jackson.databind.JsonNode;

@Controller
@RequestMapping("interface/devicePerson")
public class DevicePersonController {
	
	private static Logger logger = LogManager.getLogger(DevicePersonController.class.getName());
	@Autowired
	private PersonInfoService personInfoService;
	@Autowired
	private VehicleInfoService vehicleInfoService;
	@Autowired
	private RedisService redisService;
	@Autowired
	private AlertInfoService alertInfoService;
	/**
	 * 添加人员身份信息
	 * @param devicePersonVO
	 * @return
	 */
	@RequestMapping("personAdd")
	public ResponseEntity<Map<String,Object>> personAdd(HttpServletRequest req,@RequestBody DevicePersonVO devicePersonVO){
		Map<String, Object> retMap=new HashMap<String, Object>();
		retMap.put("alertInfo", null);
		FTPClient ftpClient=null;
		try{
			SimpleDateFormat sdf=new SimpleDateFormat("yyyy/MM/dd");
			SimpleDateFormat sdf2=new SimpleDateFormat("yyyy-MM-dd");
			String token=req.getParameter("Token");
			String info=redisService.getString(token);
			ManagerInfo managerInfo=new ManagerInfo();
			managerInfo.setManagerInfoId(JsonUtils.fromJson(info).get("managerInfoId").asLong());
			managerInfo.setManagerName(JsonUtils.fromJson(info).get("managerName").asText());
			managerInfo.setCertificateCode(JsonUtils.fromJson(info).get("certificateCode").asText());
			managerInfo.setOrganizationInfoId(JsonUtils.fromJson(info).get("organizationInfoId").asLong());
			
			PersonInfo personInfo=new PersonInfo();
			personInfo.setOrganizationInfoId(managerInfo.getOrganizationInfoId());
			personInfo.setCertificateCode(devicePersonVO.getCertificateCode());
			personInfo.setName(devicePersonVO.getName());
			personInfo.setGender(devicePersonVO.getGender());
			personInfo.setBirthday(sdf2.parse(devicePersonVO.getBirthday()));
			personInfo.setNationality(devicePersonVO.getNationality());
			personInfo.setAddress(devicePersonVO.getAddress());
			personInfo.setCertificateCodeEffectiveDate(devicePersonVO.getCertificateCodeEffectiveDate());
			personInfo.setSignOrganization(devicePersonVO.getSignOrganization());
			personInfo.setPersonType(1);
			personInfo.setState(1);
			personInfo.setCreateDate(new Date());
			PersonInfo tempPersonInfo=personInfoService.findPersonInfoByCertificateCode(personInfo.getCertificateCode());
			if(tempPersonInfo==null){
				//上传照片
				String ftp_photoDirectory="image/" + sdf.format(new Date());
				ftpClient=FtpUtil.connect(CommonUtil.getPropertiesParam("ftp_address"), Integer.parseInt(CommonUtil.getPropertiesParam("ftp_port")), CommonUtil.getPropertiesParam("ftp_user"), CommonUtil.getPropertiesParam("ftp_password"), ftp_photoDirectory);
				byte[] certificateFaceBytes=Base64Utils.decodeFromString(devicePersonVO.getCertificateFaceBase64());
				String certificateFaceFileName=FtpUtil.generateFileName("certificateFace.jpg");
				try(InputStream is=new ByteArrayInputStream(certificateFaceBytes)){
					FtpUtil.upload(certificateFaceFileName, is, ftpClient);
					personInfo.setCertificateFaceUrl(ftp_photoDirectory+"/"+certificateFaceFileName);
				}catch (Exception e) {
					logger.error(e);
				}
				if(!StringUtil.isNullOrEmpty(devicePersonVO.getPersonFaceBase64())){
					byte[] personFaceBytes=Base64Utils.decodeFromString(devicePersonVO.getPersonFaceBase64());
					String personFaceFileName=FtpUtil.generateFileName("personFace.jpg");
					try(InputStream is=new ByteArrayInputStream(personFaceBytes)){
						FtpUtil.upload(personFaceFileName, is, ftpClient);
						personInfo.setPersonFaceUrl(ftp_photoDirectory+"/"+personFaceFileName);
					}catch (Exception e) {
						logger.error(e);
					}
				}
			}else{
				personInfo.setCertificateFaceUrl(tempPersonInfo.getCertificateFaceUrl());
				personInfo.setPersonFaceUrl(tempPersonInfo.getPersonFaceUrl());
				Map<String, Object> paramMap3=new HashMap<String, Object>();
				paramMap3.put("personInfoId", tempPersonInfo.getPersonInfoId());
				paramMap3.put("alertType", 1);
				AlertInfo tempAlertInfo=alertInfoService.findAlertInfoByPersonIdAndAlertType(paramMap3);
				if(tempAlertInfo!=null){
					Map<String, Object> retAlertInfo=new HashMap<String, Object>();
					retAlertInfo.put("alertInfoId", tempAlertInfo.getAlertInfoId());
					retAlertInfo.put("alertType", tempAlertInfo.getAlertType());
					if(tempAlertInfo.getAlertType()==1){
						retAlertInfo.put("alertComment",tempAlertInfo.getAlertComment());
					}else{
						String alertCommentStr="";
						String alertJson=tempAlertInfo.getAlertComment();
						Iterator<JsonNode> zbryList=JsonUtils.fromJson(alertJson).iterator();
						int i=0;
						if(zbryList.hasNext()){
							while(zbryList.hasNext()){
								JsonNode zbry=zbryList.next();
								if(i==0){
									alertCommentStr+=(ObjectUtils.isEmpty(zbry.get("rylb"))?null:zbry.get("rylb").asText())+" "+(ObjectUtils.isEmpty(zbry.get("aqms"))?null:zbry.get("aqms").asText())+" "+(ObjectUtils.isEmpty(zbry.get("clfs"))?null:zbry.get("clfs").asText());
								}else{
									alertCommentStr+=","+(ObjectUtils.isEmpty(zbry.get("rylb"))?null:zbry.get("rylb").asText())+" "+(ObjectUtils.isEmpty(zbry.get("aqms"))?null:zbry.get("aqms").asText())+" "+(ObjectUtils.isEmpty(zbry.get("clfs"))?null:zbry.get("clfs").asText());
								}
								++i;
							}
						}
						retAlertInfo.put("alertComment",alertCommentStr);
					}
				}
			}
			VehicleInfo vehicleInfo=vehicleInfoService.findVehicleInfoByVehicleLicense(devicePersonVO.getVehicleLicense());
			String eventId=redisService.getString(vehicleInfo.getVehicleLicense()+"_eventId");
			AlertInfo alertInfo=personInfoService.addPersonInfo(personInfo, vehicleInfo,1,managerInfo,eventId);
			retMap.put("state", 1);
			retMap.put("msg", "添加成功");
			if(alertInfo!=null){
				Map<String, Object> retAlertInfo=new HashMap<String, Object>();
				retAlertInfo.put("alertInfoId", alertInfo.getAlertInfoId());
				retAlertInfo.put("alertType", alertInfo.getAlertType());
				if(alertInfo.getAlertType()==1){
					retAlertInfo.put("alertComment",alertInfo.getAlertComment());
				}else{
					String alertCommentStr="";
					String alertJson=alertInfo.getAlertComment();
					Iterator<JsonNode> zbryList=JsonUtils.fromJson(alertJson).iterator();
					int i=0;
					if(zbryList.hasNext()){
						while(zbryList.hasNext()){
							JsonNode zbry=zbryList.next();
							if(i==0){
								alertCommentStr+=(ObjectUtils.isEmpty(zbry.get("rylb"))?null:zbry.get("rylb").asText())+" "+(ObjectUtils.isEmpty(zbry.get("aqms"))?null:zbry.get("aqms").asText())+" "+(ObjectUtils.isEmpty(zbry.get("clfs"))?null:zbry.get("clfs").asText());
							}else{
								alertCommentStr+=","+(ObjectUtils.isEmpty(zbry.get("rylb"))?null:zbry.get("rylb").asText())+" "+(ObjectUtils.isEmpty(zbry.get("aqms"))?null:zbry.get("aqms").asText())+" "+(ObjectUtils.isEmpty(zbry.get("clfs"))?null:zbry.get("clfs").asText());
							}
							++i;
						}
					}
					retAlertInfo.put("alertComment",alertCommentStr);
				}
				retMap.put("alertInfo", retAlertInfo);
			}
		}catch(Exception e){
			e.printStackTrace();
			logger.error(e);
			retMap.put("state", 0);
			retMap.put("msg", "添加失败");
		}finally {
			if(ftpClient!=null){
				try{
					FtpUtil.closeConnection(ftpClient);
				}catch(Exception e){
					ftpClient=null;
				}
			}
		}
		return new ResponseEntity<Map<String,Object>>(retMap, HttpStatus.OK);
	}
	
	/**
	 * 补全人员信息
	 * @param devicePersonVO
	 * @return
	 */
	@RequestMapping("personSupplement")
	public ResponseEntity<Map<String,Object>> personSupplement(HttpServletRequest req,@RequestBody DevicePersonVO devicePersonVO){
		Map<String, Object> retMap=new HashMap<String, Object>();
		FTPClient ftpClient=null;
		try{
//			SimpleDateFormat sdf=new SimpleDateFormat("yyyy/MM/dd");
//			SimpleDateFormat sdf2=new SimpleDateFormat("yyyyMMdd");
			
			String token=req.getParameter("Token");
			String info=redisService.getString(token);
			ManagerInfo managerInfo=new ManagerInfo();
			managerInfo.setManagerInfoId(JsonUtils.fromJson(info).get("managerInfoId").asLong());
			managerInfo.setManagerName(JsonUtils.fromJson(info).get("managerName").asText());
			managerInfo.setCertificateCode(JsonUtils.fromJson(info).get("certificateCode").asText());
			managerInfo.setOrganizationInfoId(JsonUtils.fromJson(info).get("organizationInfoId").asLong());
			
			VehicleInfo vehicleInfo=vehicleInfoService.findVehicleInfoByVehicleLicense(devicePersonVO.getVehicleLicense());
			PersonInfo personInfo=personInfoService.selectByPrimaryKey(devicePersonVO.getPersonId());
			if(personInfo==null){
				retMap.put("state", 0);
				retMap.put("msg", "人员不存在");
				return new ResponseEntity<Map<String,Object>>(retMap, HttpStatus.OK);
			}
			String certificateCode=personInfo.getCertificateCode();
			personInfo.setPersonType(1);
			personInfo.setName(devicePersonVO.getName());
			personInfo.setCertificateCode(devicePersonVO.getCertificateCode());
			//调用省厅接口获取人员信息
			/*
			String getPersonurl=CommonUtil.getPropertiesParam("getPersonurl");
			Map<String, Object> map=new HashMap<String, Object>();
			map.put("username", CommonUtil.getPropertiesParam("username"));
			map.put("password", CommonUtil.getPropertiesParam("password"));
			map.put("sbid", CommonUtil.getPropertiesParam("sbid"));
			map.put("sfzh", certificateCode);
			map.put("checkId", CommonUtil.getPropertiesParam("checkId"));
			map.put("checkName", CommonUtil.getPropertiesParam("checkName"));
			String json=JsonUtils.toJson(map);
			logger.trace("获取人员请求参数"+json);
			Map<String, String> postParamMap=new HashMap<String, String>();
			postParamMap.put("jsonObj", json);
			String bodyStr=HttpClientUtil.doPost(getPersonurl, postParamMap);
			logger.trace("获取人员接收参数"+json);
			String code=JsonUtils.fromJson(bodyStr).get("code").asText();
			if("000".equals(code)){
				Iterator<JsonNode> ryxxList=JsonUtils.fromJson(bodyStr).get("data").get("ryxxList").iterator();
				while(ryxxList.hasNext()){
					JsonNode ryxx=ryxxList.next();
					personInfo.setName(ObjectUtils.isEmpty(ryxx.get("xm"))?null:ryxx.get("xm").asText());
					personInfo.setCertificateCode(certificateCode);
					personInfo.setGender(ObjectUtils.isEmpty(ryxx.get("xb"))?null:ryxx.get("xb").asText());
					personInfo.setAddress(ObjectUtils.isEmpty(ryxx.get("zzxz"))?null:ryxx.get("zzxz").asText());
					personInfo.setNationality(ObjectUtils.isEmpty(ryxx.get("mz"))?null:ryxx.get("mz").asText());
					personInfo.setBirthday(sdf2.parse(certificateCode.substring(6, 14)));
					String xp=ObjectUtils.isEmpty(ryxx.get("mz"))?null:ryxx.get("mz").asText();
					if(xp!=null){
						String ftp_photoDirectory="image/" + sdf.format(new Date());
						ftpClient=FtpUtil.connect(CommonUtil.getPropertiesParam("ftp_address"), Integer.parseInt(CommonUtil.getPropertiesParam("ftp_port")), CommonUtil.getPropertiesParam("ftp_user"), CommonUtil.getPropertiesParam("ftp_password"), ftp_photoDirectory);
						byte[] certificateFaceBytes=Base64Utils.decodeFromString(xp);
						String certificateFaceFileName=FtpUtil.generateFileName("certificateFace.jpg");
						try(InputStream is=new ByteArrayInputStream(certificateFaceBytes)){
							FtpUtil.upload(certificateFaceFileName, is, ftpClient);
							personInfo.setCertificateFaceUrl(ftp_photoDirectory+"/"+certificateFaceFileName);
						}catch (Exception e) {
							logger.error(e);
						}
					}
					break;
				}
			}*/
			String eventId=redisService.getString(vehicleInfo.getVehicleLicense()+"_eventId");
			AlertInfo alertInfo=personInfoService.supplementPerson(personInfo,vehicleInfo,certificateCode,managerInfo,eventId);
			if(alertInfo==null){
				retMap.put("state", 1);
				retMap.put("msg", "补全成功");
			}else{
				retMap.put("state", 1);
				retMap.put("msg", "补全成功");
				Map<String, Object> retAlertInfo=new HashMap<String, Object>();
				retAlertInfo.put("alertInfoId", alertInfo.getAlertInfoId());
				retAlertInfo.put("alertType", alertInfo.getAlertType());
				if(alertInfo.getAlertType()==1){
					retAlertInfo.put("alertComment",alertInfo.getAlertComment());
				}else{
					String alertCommentStr="";
					String alertJson=alertInfo.getAlertComment();
					Iterator<JsonNode> zbryList=JsonUtils.fromJson(alertJson).iterator();
					int i=0;
					if(zbryList.hasNext()){
						while(zbryList.hasNext()){
							JsonNode zbry=zbryList.next();
							if(i==0){
								alertCommentStr+=(ObjectUtils.isEmpty(zbry.get("rylb"))?null:zbry.get("rylb").asText())+" "+(ObjectUtils.isEmpty(zbry.get("aqms"))?null:zbry.get("aqms").asText())+" "+(ObjectUtils.isEmpty(zbry.get("clfs"))?null:zbry.get("clfs").asText());
							}else{
								alertCommentStr+=","+(ObjectUtils.isEmpty(zbry.get("rylb"))?null:zbry.get("rylb").asText())+" "+(ObjectUtils.isEmpty(zbry.get("aqms"))?null:zbry.get("aqms").asText())+" "+(ObjectUtils.isEmpty(zbry.get("clfs"))?null:zbry.get("clfs").asText());
							}
							++i;
						}
					}
					retAlertInfo.put("alertComment",alertCommentStr);
				}
				retMap.put("alertInfo", retAlertInfo);
			}
		}catch(Exception e){
			e.printStackTrace();
			logger.error(e);
			retMap.put("state", 0);
			retMap.put("msg", "补全失败");
		}finally {
			if(ftpClient!=null){
				try{
					FtpUtil.closeConnection(ftpClient);
				}catch(Exception e){
					ftpClient=null;
				}
			}
		}
		return new ResponseEntity<Map<String,Object>>(retMap, HttpStatus.OK);
	}
	
	
	/**
	 * 获取人员及告警
	 * @param devicePersonPageVO
	 * @return
	 */
	@RequestMapping("getPersonInfoAndAlertInfoPage")
	public ResponseEntity<Map<String,Object>> getPersonInfoAndAlertInfoPage(HttpServletRequest req,@RequestBody DevicePersonPageVO devicePersonPageVO){
		Map<String, Object> retMap=new HashMap<String, Object>();
		FTPClient ftpClient=null;
		InputStream is =null;
		try{
			retMap=personInfoService.findPersonInfoAndAlertPageByVehicleLicense(devicePersonPageVO.getVehicleLicense(), devicePersonPageVO.getCurrentPage(),devicePersonPageVO.getPageSize());
			for(Map<String,Object> map:(List<Map<String,Object>>)retMap.get("dataList")){
				Integer alertType=(Integer) map.get("alertType");
				if(alertType!=null&&alertType==2){
					String alertCommentStr="";
					String alertJson=(String) map.get("alertComment");
					Iterator<JsonNode> zbryList=JsonUtils.fromJson(alertJson).iterator();
					int i=0;
					if(zbryList.hasNext()){
						while(zbryList.hasNext()){
							JsonNode zbry=zbryList.next();
							if(i==0){
								alertCommentStr+=(ObjectUtils.isEmpty(zbry.get("rylb"))?null:zbry.get("rylb").asText())+" "+(ObjectUtils.isEmpty(zbry.get("aqms"))?null:zbry.get("aqms").asText())+" "+(ObjectUtils.isEmpty(zbry.get("clfs"))?null:zbry.get("clfs").asText());
							}else{
								alertCommentStr+=","+(ObjectUtils.isEmpty(zbry.get("rylb"))?null:zbry.get("rylb").asText())+" "+(ObjectUtils.isEmpty(zbry.get("aqms"))?null:zbry.get("aqms").asText())+" "+(ObjectUtils.isEmpty(zbry.get("clfs"))?null:zbry.get("clfs").asText());
							}
							++i;
						}
					}
					map.put("alertComment",alertCommentStr); 
				}
				ftpClient=FtpUtil.connect(CommonUtil.getPropertiesParam("ftp_address"), Integer.parseInt(CommonUtil.getPropertiesParam("ftp_port")), CommonUtil.getPropertiesParam("ftp_user"), CommonUtil.getPropertiesParam("ftp_password"));
				String certificateFaceUrl=(String) map.get("certificateFaceBase64");
				if(StringUtils.isEmpty(certificateFaceUrl)){
					certificateFaceUrl=(String) map.get("personFaceBase64");
					int changeWorkingLength = certificateFaceUrl.split("/").length-1;
					if(changeWorkingLength>0){
						FtpUtil.changeWorkingDirectory(certificateFaceUrl.substring(0, certificateFaceUrl.lastIndexOf("/")), ftpClient);
						is=FtpUtil.retrieveFileStream(certificateFaceUrl.substring(certificateFaceUrl.lastIndexOf("/")+1,certificateFaceUrl.length()), ftpClient);
					}else{
						is=FtpUtil.retrieveFileStream(certificateFaceUrl, ftpClient);
					}
					try(ByteArrayOutputStream outStream = new ByteArrayOutputStream()){
						 byte[] buffer = new byte[1024];     
					     int len = -1;     
					     while((len = is.read(buffer)) != -1){     
					        outStream.write(buffer, 0, len);      
					     }   
					     map.put("faceBase64",Base64Utils.encodeToString(outStream.toByteArray())); 
					}catch (Exception e) {
						logger.error(e);
					}
//					for(int i=0;i<changeWorkingLength;i++){
//						FtpUtil.changeToParentDirectory(ftpClient);
//					}
				}else{
					int changeWorkingLength = certificateFaceUrl.split("/").length-1;
					if(changeWorkingLength>0){
						FtpUtil.changeWorkingDirectory(certificateFaceUrl.substring(0, certificateFaceUrl.lastIndexOf("/")), ftpClient);
						is=FtpUtil.retrieveFileStream(certificateFaceUrl.substring(certificateFaceUrl.lastIndexOf("/")+1,certificateFaceUrl.length()), ftpClient);
					}else{
						is=FtpUtil.retrieveFileStream(certificateFaceUrl, ftpClient);
					}
					try(ByteArrayOutputStream outStream = new ByteArrayOutputStream()){
						 byte[] buffer = new byte[1024];     
					     int len = -1;     
					     while((len = is.read(buffer)) != -1){     
					        outStream.write(buffer, 0, len);      
					     }   
					     map.put("faceBase64",Base64Utils.encodeToString(outStream.toByteArray())); 
					}catch (Exception e) {
						logger.error(e);
					}
//					for(int i=0;i<changeWorkingLength;i++){
//						FtpUtil.changeToParentDirectory(ftpClient);
//					}
				}
				if("3".equals(map.get("personType")+"")){
					map.put("certificateCode",null);
				}
				map.remove("certificateFaceBase64");
				map.remove("personFaceBase64");
				if(ftpClient!=null){
					try{
						FtpUtil.closeConnection(ftpClient);
					}catch(Exception e){
						ftpClient=null;
					}
				}
			}
			retMap.put("state", 1);
			retMap.put("msg", "查询成功");
		}catch(Exception e){
			e.printStackTrace();
			logger.error(e);
			retMap.put("state", 0);
			retMap.put("msg", "查询失败");
		}finally {
			if(ftpClient!=null){
				try{
					FtpUtil.closeConnection(ftpClient);
				}catch(Exception e){
					ftpClient=null;
				}
			}
			if(is!=null){
				try{
					is.close();
				}catch(Exception e){
					is=null;
				}
			}
		}
		return new ResponseEntity<Map<String,Object>>(retMap, HttpStatus.OK);
	}
	
}
